package com.shiwaixiangcun.authz.shiro.filter;

import com.shiwaixiangcun.core.domain.oauth.AccessToken;
import com.shiwaixiangcun.core.service.oauth.OAuthRSService;
import com.shiwaixiangcun.core.shiro.AccessTokenContextHolder;
import org.apache.shiro.web.servlet.OncePerRequestFilter;
import org.springframework.beans.factory.annotation.Autowired;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

/**
 * Created by Administrator on 2017/5/10.
 */
public class AccessTokenContextFilter extends OncePerRequestFilter {
    @Autowired
    private OAuthRSService rsService;

    @Override
    protected void doFilterInternal(ServletRequest request, ServletResponse response, FilterChain chain) throws ServletException, IOException {
        HttpServletRequest httpRequest = (HttpServletRequest) request;
        final String accessToken = AccessToken.getAccessToken(httpRequest);
        AccessToken token = rsService.loadAccessTokenByTokenId(accessToken);
        AccessTokenContextHolder.set(token);
        chain.doFilter(request, response);
        AccessTokenContextHolder.remove();
    }
}
